<?php
namespace ns_model\center_op;
//use ns_model\delivery\cdn_delivery_explain;

\ns_core\m_load::load("ns_model.m_queue_medel");
\ns_core\m_load::load("ns_model.center_op.center_op_explain");
\ns_core\m_load::load("ns_model.center_import.center_import_logic");
\ns_core\m_load::load("ns_model.command.command");
\ns_core\m_load::load("ns_model.command.command_task");
\ns_core\m_load::load("ns_data_model.queue.m_center_op_inout");
\ns_core\m_load::load("ns_data_model.command.m_command_inout");
/**
 * 中心同步指令执行
 */
class center_op_queue extends \ns_model\center_op\center_op_explain
{

    /**
     * 对CDN注入队列的解释
     * 确认队列执行条件等
     */
    public function explain()
    {
        return \m_config::return_data(NS_CDS_SUCCE,"ok");
    }

    /**
     * 累加中心同步指令队列
     * @param $message
     */
    public function push($message)
    {
        $m_queue_model = new \ns_model\m_queue_model();
        //查询媒资基本元数据信息
        $result_info = $m_queue_model->_get_queue_info($message['base_info']['nns_id'],$message['base_info']['nns_video_type'],true);
        if($result_info['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($result_info,true), $message['base_info']['nns_cp_id']);
            return $result_info;
        }
        //封装媒资元数据名称为界面展示
        $result_info_name = $m_queue_model->_get_queue_name($message['base_info']['nns_video_type'], $result_info['data_info']);
        if($result_info_name['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($result_info_name,true), $message['base_info']['nns_cp_id']);
            return $result_info_name;
        }

        //获取CP绑定的SP，并封装中心同步指令元数据
        $push_params = $this->get_op_queue_params($message,$result_info['data_info']);
        if($push_params['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($push_params,true), $message['base_info']['nns_cp_id']);
            return $push_params;
        }

        $push_info = $push_params['data_info'];
        $push_info['base_info']['nns_name'] = $result_info_name['data_info'];
        $center_op_re = \m_config::return_data(NS_CDS_SUCCE,'初始化成功状态');
        /************************指令池*************************/

        if($message['base_info']['nns_video_type'] === NS_CDS_LIVE_MEDIA)
        {
            $original_id = $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_content_id'];
        }
        elseif($message['base_info']['nns_video_type'] === NS_CDS_PLAYBILL)
        {
            $original_id = $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_playbill_import_id'];
        }
        elseif($message['base_info']['nns_video_type'] === NS_CDS_VIDEO )
        {
            $original_id = $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_asset_import_id'];
        }
        else
        {
            $original_id = $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_import_id'];
        }

        $command_arr = array(
            'base_info' => array(
                'nns_message_id' => $push_info['base_info']['nns_message_id'],
                'nns_source_id' => $push_info['base_info']['nns_cp_id'],
                'nns_type' => $message['base_info']['nns_video_type'],
                'nns_original_id' => $original_id,
                'nns_name' => $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_name'],
                'nns_content_id' => $message['base_info']['nns_id'],
            )
        );

        $command = new \ns_model\command\command();

        //指令池查询 【command查询】
        $query_command_arr = array(
            'base_info' => array(
                'nns_message_id' => $push_info['base_info']['nns_message_id'],
            ),
        );
        $query_command = $command->query($query_command_arr);
        unset($query_command_arr);
        if ($query_command['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']查询指令池失败：' . var_export($query_command,true), $message['base_info']['nns_cp_id']);
        }
        if (!empty($query_command['data_info']) && is_array($query_command['data_info']) && count($query_command['data_info']) > 0)
        {
            $bool_command_exist = false;
            foreach ($query_command['data_info'] as $val)
            {
                $arr = array(
                    'nns_message_id' => $val['nns_message_id'],
                    'nns_source_id' => $val['nns_source_id'],
                    'nns_type' => $val['nns_type'],
                    'nns_original_id' => $val['nns_original_id'],
                    'nns_name' => $val['nns_name'],
                    'nns_content_id' => $val['nns_content_id'],
                );
                //对比数据，新入数据与command数据
                $diff_arr = array_diff($command_arr['base_info'], $arr);
                //存在相同的command队列数据
                if (empty($diff_arr))
                {
                    $bool_command_exist = true;
                    $command_re["data_info"]["info"]["out"]["base_info"]["nns_id"] = $val['nns_id'];
                    continue;
                }
            }
            unset($diff_arr);unset($arr);
            if ($bool_command_exist)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令池已经存在：' . var_export($command_arr, true), $message['base_info']['nns_cp_id']);
            }
            else
            {
                //不存在相同的command数据，则插入command
                $command_re = $command->push($command_arr);
                unset($command);
                if($command_re['ret'] != NS_CDS_SUCCE)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']不存在相同的指令池，生成失败：' . var_export($command_re,true), $message['base_info']['nns_cp_id']);
                    return $command_re;
                }
            }
        }
        else
        {
            //插入command
            $command_re = $command->push($command_arr);
            unset($command);
            if($command_re['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']生成指令池失败：' . var_export($command_re,true), $message['base_info']['nns_cp_id']);
                return $command_re;
            }
        }
        $command_id = $command_re["data_info"]["info"]["out"]["base_info"]["nns_id"];
        /************************指令池*************************/
        /************************指令状态池*************************/
        $op_sp_arr = $push_info['sp_info'];
        $command_task = new \ns_model\command\command_task();
        foreach ($op_sp_arr as $sp)
        {
            if(empty($sp))
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']当前SP为空，跳过处理', $message['base_info']['nns_cp_id']);
                continue;
            }

            $command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                    'nns_sp_id' => $sp,
                    'nns_action' => $push_info['base_info']['nns_action'],
                    'nns_status' => 1, //等待注入
                    'nns_mtime' => round(microtime(TRUE) * 1000),
                )
            );

            $compare_command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                    'nns_sp_id' => $sp,
                    'nns_action' => $push_info['base_info']['nns_action'],
                )
            );
            //指令状态池查询【command_task查询】
            $query_command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                )
            );
            $query_command_task = $command_task->query($query_command_task_arr);
            unset($query_command_task_arr);
            if ($query_command_task['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池查询失败：' . var_export($query_command_task,true), $message['base_info']['nns_cp_id']);
            }
            if (!empty($query_command_task['data_info']) && is_array($query_command_task['data_info']) && count($query_command_task['data_info']) > 0)
            {
                $bool_command_task_exist = false;
                foreach ($query_command_task['data_info'] as $val)
                {
                    $arr = array(
                        'nns_command_id' => $val['nns_command_id'],
                        'nns_sp_id' => $val['nns_sp_id'],
                        'nns_action' => $val['nns_action'],
                    );
                    //对比数据，新入数据与command_task数据
                    $diff_arr = array_diff($compare_command_task_arr['base_info'], $arr);
                    //存在相同的command_task队列数据
                    if (empty($diff_arr))
                    {
                        $bool_command_task_exist = true;
                        $command_task_re["data_info"]["info"]["out"]["base_info"]["nns_id"] = $val['nns_id'];
                        continue;
                    }
                }
                unset($diff_arr);unset($arr);
                //存在相同的队列状态池
                if ($bool_command_task_exist)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池数据已存在：' . var_export($query_command_task,true), $message['base_info']['nns_cp_id']);
                    //modify by zhiyong.luo 2018-09-27 ps:即使存在相同的队列状态池【command_task存在相同的数据】,则应该生成队列到中心同步指令，而不是直接返回
                    //continue;
                }
                else//不存在相同的队列状态池
                {
                    $command_task_re = $command_task->push($command_task_arr);
                    if($command_task_re['ret'] != NS_CDS_SUCCE)
                    {
                        \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']不存在相同的指令状态池，生成失败：' . var_export($command_task_re,true), $message['base_info']['nns_cp_id']);
                        return $command_task_re;
                    }
                }
            }
            else
            {
                $command_task_re = $command_task->push($command_task_arr);
                if($command_task_re['ret'] != NS_CDS_SUCCE)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池生成失败' . var_export($command_task_re,true), $message['base_info']['nns_cp_id']);
                    return $command_task_re;
                }
            }
            //进入中心队列
            $push_info['base_info']['nns_command_task_id'] = $command_task_re["data_info"]["info"]["out"]["base_info"]["nns_id"];
            $push_info['base_info']['nns_org_id'] = $sp;
            $obj_excute = new \m_center_op_inout();
            $center_op_re = $obj_excute->add($push_info);

            if($center_op_re['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']生成中心同步队列失败，原因可能存在相同的中心同步队列数据或者其它，插入结果：' . var_export($center_op_re,true), $message['base_info']['nns_cp_id']);
                return $center_op_re;
            }
        }
        unset($command_task);
        /************************指令状态池*************************/
        return $center_op_re;
    }

    /**
     * 抛出中心同步指令队列
     */
	public function pop($wait_num=20, $video_type = 'video')
	{
	    //c2队列允许最大
        $video_num_type = 'cdn_' . $video_type . '_max';
        $data_num = 100;
        if($video_type == 'playbill')
        {
            if($this->arr_sp_config['playbill']['enabled'] == 1)
            {
                $data_num = (isset($this->arr_sp_config['playbill']['group_num']) && (int)$this->arr_sp_config['playbill']['group_num'] > 0) ? (int)$this->arr_sp_config['playbill']['group_num'] : 6000;
            }
        }
        else
        {
            $data_num = (isset($this->arr_sp_config[$video_num_type]) && (int)$this->arr_sp_config[$video_num_type] > 0) ? (int)$this->arr_sp_config[$video_num_type] : 100 ;
        }
        //c2队列根据策略的现行数量
        if ($video_type == NS_CDS_EPG_FILE)
        {
            //EPGFile
            $c2_arr = $this->get_file_num_arr();
        }
        else
        {
            $c2_arr = $this->get_c2_num_arr();
        }

        if ($c2_arr['ret'] !=0)
        {
            return \m_config::return_data(NS_CDS_FAIL, '查询c2队列失败,' . $c2_arr['reason']);
        }

        if ((int)$data_num <= (int)$c2_arr['data_info'][0]['num'])
        {
            return \m_config::return_data(NS_CDS_FAIL, 'c2队列该【' . $video_type . '】类型已经达到最大值');
        }
        $limit = null;
        if (((int)$data_num - (int)$c2_arr['data_info'][0]['num']) >= $wait_num)
        {
            $limit = $wait_num;
        }
        else
        {
            $limit = (int)$data_num - (int)$c2_arr['data_info'][0]['num'];
        }
        if ($video_type == "playbill"  && isset($this->arr_sp_config['playbill']['enabled']) && $this->arr_sp_config['playbill']['enabled'] == '1')
        {
            $op_queue = $this->playbill_get_op_queue_list($video_type, $limit);
        }
        else
        {
            $op_queue = $this->get_op_queue_list($video_type, $limit);
        }
        if($op_queue['ret'] != NS_CDS_SUCCE || !is_array($op_queue['data_info']) || empty($op_queue['data_info']))
        {
            return \m_config::return_data(NS_CDS_FAIL,'中心同步指令注入数据队列查询失败或者数据为空');
        }
        /***************查询中心同步指令任务的媒资信息******************/
        $mixed_info = $this->query_mixed_info($op_queue['data_info']);
        if($mixed_info['ret'] != NS_CDS_SUCCE)
        {
            return \m_config::return_data(NS_CDS_FAIL,'中心同步指令注入数据的媒资信息查询失败');
        }
        return \m_config::return_data(NS_CDS_SUCCE,'ok',$mixed_info['data_info']);
    }

    /**
     * 指定sp注入
     * @param $message
     * @return array
     */
    public function push_one($message)
    {
        $m_queue_model = new \ns_model\m_queue_model();
        $result_info = $m_queue_model->_get_queue_info($message['base_info']['nns_id'],$message['base_info']['nns_video_type'],true);
        if($result_info['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($result_info,true), $message['base_info']['nns_cp_id']);
            return $result_info;
        }
        $result_info_name = $m_queue_model->_get_queue_name($message['base_info']['nns_video_type'], $result_info['data_info']);
        if($result_info_name['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($result_info_name,true), $message['base_info']['nns_cp_id']);
            return $result_info_name;
        }

        //获取CP绑定的SP
        $push_params = $this->get_op_queue_params($message,$result_info['data_info']);
        if($push_params['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']' . var_export($push_params,true), $message['base_info']['nns_cp_id']);
            return $push_params;
        }
        $push_info = $push_params['data_info'];
        unset($push_info['sp_info']);
        $push_info['sp_info'] = array($this->str_sp_id);
        $push_info['base_info']['nns_name'] = $result_info_name['data_info'];
        $center_op_re = \m_config::return_data(NS_CDS_SUCCE,'初始化成功状态');
        /************************指令池*************************/
        $original_id = $message['base_info']['nns_video_type'] === NS_CDS_VIDEO ? $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_asset_import_id'] : $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_import_id'];

        $command_arr = array(
            'base_info' => array(
                'nns_message_id' => $push_info['base_info']['nns_message_id'],
                'nns_source_id' => $push_info['base_info']['nns_cp_id'],
                'nns_type' => $message['base_info']['nns_video_type'],
                'nns_original_id' => $original_id,
                'nns_name' => $result_info['data_info'][$message['base_info']['nns_video_type']]['base_info']['nns_name'],
                'nns_content_id' => $message['base_info']['nns_id'],
            )
        );

        $command = new \ns_model\command\command();

        //指令池查询 【command查询】
        $query_command_arr = array(
            'base_info' => array(
                'nns_message_id' => $push_info['base_info']['nns_message_id'],
            ),
        );
        $query_command = $command->query($query_command_arr);
        unset($query_command_arr);
        if ($query_command['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']查询指令池失败：' . var_export($query_command,true), $message['base_info']['nns_cp_id']);
        }

        if (!empty($query_command['data_info']) && is_array($query_command['data_info']) && count($query_command['data_info']) > 0)
        {
            $bool_command_exist = false;
            foreach ($query_command['data_info'] as $val)
            {
                $arr = array(
                    'nns_message_id' => $val['nns_message_id'],
                    'nns_source_id' => $val['nns_source_id'],
                    'nns_type' => $val['nns_type'],
                    'nns_original_id' => $val['nns_original_id'],
                    'nns_name' => $val['nns_name'],
                    'nns_content_id' => $val['nns_content_id'],
                );
                //对比数据，新入数据与command数据
                $diff_arr = array_diff($command_arr['base_info'], $arr);
                //存在相同的command队列数据
                if (empty($diff_arr))
                {
                    $bool_command_exist = true;
                    $command_re["data_info"]["info"]["out"]["base_info"]["nns_id"] = $val['nns_id'];
                    continue;
                }
            }
            unset($diff_arr);unset($arr);
            if ($bool_command_exist)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令池已经存在：' . var_export($command_arr, true), $message['base_info']['nns_cp_id']);
            }
            else
            {
                //不存在相同的command数据，则插入command
                $command_re = $command->push($command_arr);
                unset($command);
                if($command_re['ret'] != NS_CDS_SUCCE)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']不存在相同的指令池，生成失败：' . var_export($command_re,true), $message['base_info']['nns_cp_id']);
                    return $command_re;
                }
            }
        }
        else
        {
            //插入command
            $command_re = $command->push($command_arr);
            unset($command);
            if($command_re['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']生成指令池失败：' . var_export($command_re,true), $message['base_info']['nns_cp_id']);
                return $command_re;
            }
        }
        $command_id = $command_re["data_info"]["info"]["out"]["base_info"]["nns_id"];
        /************************指令池*************************/

        /************************指令状态池*************************/
        $op_sp_arr = $push_info['sp_info'];
        $command_task = new \ns_model\command\command_task();
        foreach ($op_sp_arr as $sp)
        {
            if(empty($sp))
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']当前SP为空，跳过处理', $message['base_info']['nns_cp_id']);
                continue;
            }

            $command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                    'nns_sp_id' => $sp,
                    'nns_action' => $push_info['base_info']['nns_action'],
                    'nns_status' => 1, //等待注入
                    'nns_mtime' => round(microtime(TRUE) * 1000),
                )
            );

            $compare_command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                    'nns_sp_id' => $sp,
                    'nns_action' => $push_info['base_info']['nns_action'],
                )
            );
            //指令状态池查询【command_task查询】
            $query_command_task_arr = array(
                'base_info' => array(
                    'nns_command_id' => $command_id,
                )
            );
            $query_command_task = $command_task->query($query_command_task_arr);
            unset($query_command_task_arr);
            if ($query_command_task['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池查询失败：' . var_export($query_command_task,true), $message['base_info']['nns_cp_id']);
            }

            if (!empty($query_command_task['data_info']) && is_array($query_command_task['data_info']) && count($query_command_task['data_info']) > 0)
            {
                $bool_command_task_exist = false;
                foreach ($query_command_task['data_info'] as $val)
                {
                    $arr = array(
                        'nns_command_id' => $val['nns_command_id'],
                        'nns_sp_id' => $val['nns_sp_id'],
                        'nns_action' => $val['nns_action'],
                    );
                    //对比数据，新入数据与command_task数据
                    $diff_arr = array_diff($compare_command_task_arr['base_info'], $arr);
                    //存在相同的command_task队列数据
                    if (empty($diff_arr))
                    {
                        $bool_command_task_exist = true;
                        $command_task_re["data_info"]["info"]["out"]["base_info"]["nns_id"] = $val['nns_id'];
                        continue;
                    }
                }
                unset($diff_arr);unset($arr);
                //存在相同的队列状态池
                if ($bool_command_task_exist)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池数据已存在：' . var_export($query_command_task,true), $message['base_info']['nns_cp_id']);
                    //modify by zhiyong.luo 2018-09-27 ps:即使存在相同的队列状态池【command_task存在相同的数据】,则应该生成队列到中心同步指令，而不是直接返回
                    //continue;
                }
                else//不存在相同的队列状态池
                {
                    $command_task_re = $command_task->push($command_task_arr);
                    if($command_task_re['ret'] != NS_CDS_SUCCE)
                    {
                        \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']不存在相同的指令状态池，生成失败：' . var_export($command_task_re,true), $message['base_info']['nns_cp_id']);
                        return $command_task_re;
                    }
                }
            }
            else
            {
                $command_task_re = $command_task->push($command_task_arr);
                if($command_task_re['ret'] != NS_CDS_SUCCE)
                {
                    \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']指令状态池生成失败' . var_export($command_task_re,true), $message['base_info']['nns_cp_id']);
                    return $command_task_re;
                }
            }

            //进入中心队列
            $push_info['base_info']['nns_command_task_id'] = $command_task_re["data_info"]["info"]["out"]["base_info"]["nns_id"];
            $push_info['base_info']['nns_org_id'] = $sp;
            $obj_excute = new \m_center_op_inout();
            $center_op_re = $obj_excute->add($push_info);
            if($center_op_re['ret'] != NS_CDS_SUCCE)
            {
                \m_config::write_message_execute_log('[消息为' . $message['base_info']['nns_message_id'] . ']生成中心同步队列失败，原因可能存在相同的中心同步队列数据或者其它，插入结果：' . var_export($center_op_re,true), $message['base_info']['nns_cp_id']);
                return $center_op_re;
            }
        }
        unset($command_task);
        /************************指令状态池*************************/
        return $center_op_re;
    }
}